<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="用户名称" prop="userName">
        <el-input maxlength="50"
                  class="search-width"
                  v-model="queryParams.userName"
                  placeholder="请输入用户名称"
                  clearable
                  @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时间" prop="time" v-if="changeAuth">
        <el-date-picker
            class="search-width"
            v-model="queryParams.time"
            type="month"
            format="YYYY-MM"
            value-format="YYYY-MM"
            placeholder="请选择时间"
            :clearable="false"
            :editable="false"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['biz:bizWages:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['biz:bizWages:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['biz:bizWages:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['biz:bizWages:import']">导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['biz:bizWages:export']">导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bizWagesList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="left"/>
      <el-table-column label="序号" type="index" align="left" width="60"/>
      <el-table-column label="用户名称" align="left" prop="userName" width="150"/>
      <el-table-column label="出勤天数" align="left" prop="workDays" width="100"/>
      <el-table-column label="基本工资" align="left" prop="baseWages" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.baseWages)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="本月绩效" align="left" prop="month" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.month)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="预发绩效" align="left" prop="advance" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.advance)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="工龄津贴" align="left" prop="seniority" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.seniority)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="岗技津贴" align="left" prop="post" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.post)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="竞业限制津贴" align="left" prop="competition" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.competition)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="保密津贴" align="left" prop="secrecy" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.secrecy)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="安全责任津贴" align="left" prop="safe" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.safe)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="兼岗津贴" align="left" prop="job" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.job)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="老带新培训金" align="left" prop="teach" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.teach)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="其他津贴" align="left" prop="other" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.other)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="节日福利" align="left" prop="holiday" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.holiday)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="加班补贴" align="left" prop="overtime" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.overtime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="合计" align="left" prop="totalAll" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.totalAll)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="代扣代缴社保医保" align="left" prop="subWithholding" width="140">
        <template #default="scope">
          <span>{{formatMoney(scope.row.subWithholding)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="扣减预发绩效" align="left" prop="subAdvance" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.subAdvance)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="扣减请假" align="left" prop="subLeave" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.subLeave)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="应发合计" align="left" prop="totalShould" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.totalShould)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="代扣个税" align="left" prop="subTax" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.subTax)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="其他代扣" align="left" prop="subOther" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.subOther)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="实发合计" align="left" prop="totalReal" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.totalReal)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="累计预发绩效" align="left" prop="totalAdvance" width="120">
        <template #default="scope">
          <span>{{formatMoney(scope.row.totalAdvance)}}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="left" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['biz:bizWages:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['biz:bizWages:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改工资条对话框 -->
    <el-dialog :close-on-click-modal="false" draggable :title="title" v-model="open" width="1200px" append-to-body @close="cancel">
      <el-form ref="bizWagesRef" :model="form" :rules="rules" label-width="140px">

        <el-row>
          <el-col :span="6">
            <el-form-item label="时间" prop="userName">
              <el-date-picker :disabled="isUpdate"
                              class="input-width"
                              v-model="form.time"
                              type="month"
                              format="YYYY-MM"
                              value-format="YYYY-MM"
                              placeholder="请选择时间"
                              :clearable="false"
                              :editable="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="用户" prop="userName">
              <el-button :disabled="isUpdate" class="input-width" @click="openSelectUser">{{
                  form.userName || '请选择用户'
                }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="出勤天数" prop="workDays">
              <el-input-number class="input-width" maxlength="50" v-model="form.workDays" placeholder="出勤天数"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="基本工资" prop="baseWages">
              <CurrencyInput maxlength="50" v-model="form.baseWages" placeholder="请输入基本工资"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="本月绩效" prop="month">
              <CurrencyInput maxlength="50" v-model="form.month" placeholder="请输入本月绩效"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预发绩效" prop="advance">
              <CurrencyInput maxlength="50" v-model="form.advance" placeholder="请输入预发绩效"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="工龄津贴" prop="seniority">
              <CurrencyInput maxlength="50" v-model="form.seniority" placeholder="请输入工龄津贴"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="岗技津贴" prop="post">
              <CurrencyInput maxlength="50" v-model="form.post" placeholder="请输入岗技津贴"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="竞业限制津贴" prop="competition">
              <CurrencyInput maxlength="50" v-model="form.competition" placeholder="请输入竞业限制津贴"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="保密津贴" prop="secrecy">
              <CurrencyInput maxlength="50" v-model="form.secrecy" placeholder="请输入保密津贴"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="安全责任津贴" prop="safe">
              <CurrencyInput maxlength="50" v-model="form.safe" placeholder="请输入安全责任津贴"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="兼岗津贴" prop="job">
              <CurrencyInput maxlength="50" v-model="form.job" placeholder="请输入兼岗津贴"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="老带新培训金" prop="teach">
              <CurrencyInput maxlength="50" v-model="form.teach" placeholder="请输入老带新培训金"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="其他津贴" prop="other">
              <CurrencyInput maxlength="50" v-model="form.other" placeholder="请输入其他津贴"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="节日福利" prop="holiday">
              <CurrencyInput maxlength="50" v-model="form.holiday" placeholder="请输入节日福利"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="加班补贴" prop="overtime">
              <CurrencyInput maxlength="50" v-model="form.overtime" placeholder="请输入加班补贴"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="代扣代缴社保医保" prop="subWithholding">
              <CurrencyInput maxlength="50" v-model="form.subWithholding" placeholder="请输入代扣代缴社保医保"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="扣减预发绩效" prop="subAdvance">
              <CurrencyInput maxlength="50" v-model="form.subAdvance" placeholder="请输入扣减预发绩效"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="扣减请假" prop="subLeave">
              <CurrencyInput maxlength="50" v-model="form.subLeave" placeholder="请输入扣减请假"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="代扣个税" prop="subTax">
              <CurrencyInput maxlength="50" v-model="form.subTax" placeholder="请输入代扣个税"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="其他代扣" prop="subOther">
              <CurrencyInput maxlength="50" v-model="form.subOther" placeholder="请输入其他代扣"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="累计预发绩效" prop="totalAdvance">
              <CurrencyInput maxlength="50" v-model="form.totalAdvance" placeholder="请输入累计预发绩效"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" maxlength="500" v-model="form.memo" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :close-on-click-modal="false" draggable :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-text>时间：</el-text>
      <el-date-picker
          class="input-width"
          v-model="upload.time"
          type="month"
          format="YYYY-MM"
          value-format="YYYY-MM"
          placeholder="请选择时间"
          :clearable="false"
          :editable="false"
      />
      <el-upload style="margin-top: 20px" ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?time=' + upload.time + '&updateSupport=' + upload.updateSupport"
                 :disabled="upload.isUploading"
                 :before-upload="handleFileChange"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport"/>
              更新已经存在的数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                     @click="importTemplate">下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
      <div v-html="importResult" style="color: red"></div>
    </el-dialog>
    <selectUser ref="selectRef" @ok="handleSelectUser"/>
  </div>
</template>

<script setup name="BizWages">
import {listBizWages, getBizWages, delBizWages, addBizWages, updateBizWages,getChangeAuth} from "@/api/biz/bizWages";
import selectUser from "@/views/system/user/selectUser";
import CurrencyInput from '@/components/CurrencyInput.vue';
import {currentDate} from '@/utils/dateutil';
import {getToken} from "@/utils/auth";
import {formatMoney} from '@/utils/money';

const {proxy} = getCurrentInstance();

const bizWagesList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isUpdate = ref(false);
const importResult = ref("");
const changeAuth = ref(false);
/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  updateSupport: 0,
  time: formatLastMonth(new Date()),
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/biz/bizWages/importExcel"
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    time: formatLastMonth(new Date())
  },
  rules: {}
});

const {queryParams, form, rules} = toRefs(data);

function openSelectUser() {
  proxy.$refs["selectRef"].show();
}

function handleSelectUser(data) {
  form.value.userCode = data.value[0].userCode;
  form.value.userName = data.value[0].nickName;
  form.value.userId = data.value[0].userId;
}

/** 查询工资条列表 */
function getList() {
  loading.value = true;
  listBizWages(queryParams.value).then(response => {
    bizWagesList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "工资条导入";
  upload.open = true;
};

/** 下载模板操作 */
function importTemplate() {
  proxy.download('biz/bizWages/download', {}, `工资条模板-${currentDate()}.xlsx`)
};

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

const handleFileChange = (event, file, fileList) => {
  importResult.value = "";
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  if (response.code == 200) {
    upload.open = false;
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
    getList();
  } else {
    importResult.value = response.msg;
  }
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

// 表单重置
function reset() {
  form.value = {
    id: null,
    createTime: null,
    updateTime: null,
    deleted: null,
    userCode: null,
    userName: null,
    workDays: null,
    baseWages: null,
    month: null,
    advance: null,
    seniority: null,
    post: null,
    competition: null,
    secrecy: null,
    safe: null,
    job: null,
    teach: null,
    other: null,
    holiday: null,
    overtime: null,
    totalAll: null,
    subWithholding: null,
    subAdvance: null,
    subLeave: null,
    totalShould: null,
    subTax: null,
    subOther: null,
    totalReal: null,
    totalAdvance: null,
    userId: null,
    memo: null,
    time: formatLastMonth(new Date())
  };
  isUpdate.value = false;
  proxy.resetForm("bizWagesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加工资条";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  isUpdate.value = true;
  const _id = row.id || ids.value
  getBizWages(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改工资条";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bizWagesRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBizWages(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBizWages(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除工资条数据项？').then(function () {
    return delBizWages(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  if (!queryParams.value.time) {
    proxy.$modal.msgError("请选择要导出的时间");
    return;
  }
  proxy.download('biz/bizWages/export', {
    ...queryParams.value
  }, `工资条-${currentDate()}.xlsx`)
}

function formatLastMonth(currentDate) {
  // 创建一个新的日期对象，设置为当前日期的上一个月
  const date = new Date(currentDate);
  date.setMonth(currentDate.getMonth() - 1);
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  if (month < 10) {
    month = '0' + month;
  }
  return `${year}-${month}`;
}

getList();
getChangeAuth(form.value).then(response => {
  changeAuth.value = response.data;
});
</script>
